//
//  RecordViewController.m
//  Zhiche-Carriage
//
//  Created by LeeBruce on 16/11/15.
//  Copyright © 2016年 LeeBruce. All rights reserved.
//

#import "RecordViewController.h"
#import "RLNetworkHelper.h"//网络判断
#import "UIView+jmCategory.h"
#import "RootViewController.h"
#import "TopBackView.h"
#import "NullView.h"
#import "RecordCell.h"
#import "ScanVC.h"
#import "OrderdetailVC.h"
#import "DeclareViewController.h"

#import "AccidentsList.h"

@interface RecordViewController ()
<
    UITableViewDelegate,
    UITableViewDataSource
>
@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, assign) int pageNo;

@property (nonatomic, assign) NSInteger pageTotal;

@property (nonatomic, strong) UIView *netView;
@property (nonatomic, strong) WKProgressHUD *hud;

@property (nonatomic, strong) NullView *nullView;

@property (nonatomic, strong) TopBackView *topBackView;

@property (nonatomic, strong) NSMutableArray<AccidentsList *>* flow_Data_Array;
@end

@implementation RecordViewController
#pragma mark -
#pragma mark - Lazy
- (TopBackView *)topBackView {
    if (!_topBackView) {
        
        CGRect frame = CGRectMake(0, 0, screenWidth, 64);
        _topBackView = [[TopBackView alloc] initWithFrame:frame
                                                     title:@"申报纪录"];
        
        _topBackView.leftButton.hidden = YES;
        
        [_topBackView.rightButton setTitle:@"事故申报"
                                  forState:UIControlStateNormal];
        _topBackView.rightButton.titleLabel.font = Font(14);
        
        [_topBackView.rightButton setTitleColor:WhiteColor
                                       forState:UIControlStateNormal];
    
        [_topBackView.rightButton addTarget:self
                                     action:@selector(naviRightButtonClick)
                           forControlEvents:UIControlEventTouchUpInside];
    }
    return _topBackView;
}
- (NullView *)nullView {
    if (!_nullView) {
        CGRect frame = CGRectMake(0, 0, screenWidth, screenHeight  - 45 * kHeight);
        
        _nullView = [[NullView  alloc]initWithFrame:frame
                                           andTitle:@"暂无记录"
                                           andImage:[UIImage imageNamed:@"no_order"]];
        _nullView.backgroundColor = GrayColor;
    }
    return _nullView;
}
- (UIView *)netView {
    if (!_netView) {
        _netView = [UIView noInternet:@"网络连接失败，请检查网络设备"
                                  and:self
                               action:@selector(NoNetPressBtn)
                            andCGreck:CGRectMake(0, 0, Main_Width, Main_height-64)];
    }
    return _netView;
}
- (UITableView *)tableView {
    if (!_tableView) {
        CGRect frame = CGRectMake(0, 64, screenWidth, screenHeight - 64 - 48 * kHeight);
        _tableView = [[UITableView alloc]initWithFrame:frame];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = GrayColor;
        _tableView.tableFooterView = [[UIView alloc]init];
    }
    return _tableView;
}


#pragma mark -
#pragma mark -  初始化Vc
- (void)viewDidLoad {
    [super viewDidLoad];

    ///0. 初始化数据
    [self initData];
    
    ///1. 设置UI
    [self setUpUI];
    

    ///2. 判断是否有网
    [self judgeNetWork];
    
}


#pragma mark -
#pragma mark - 初始化数据
- (void)initData {
    self.flow_Data_Array = @[].mutableCopy;
    self.pageNo = 1;
}
- (void)getDataToServer{
    
    NSString *urlString = [NSString stringWithFormat:@"%@?pageNo=%d&pageSize=%@",accident_list,self.pageNo,@"10"];
    
    NSLog(@"%@", urlString);
    
    [Common requestWithUrlString:urlString
                     contentType:application_json
                       errorShow:YES
                        finished:^(id responseObj) {
        
        
        
        self.pageTotal = [responseObj[@"data"][@"page"][@"totalPage"] integerValue];
        
        if ([responseObj[@"success"] boolValue]) {
            
            [self.hud dismiss:YES];
            
            if (self.pageNo == 1) {
                
                [self.flow_Data_Array removeAllObjects];
                
            }
            

            NSArray *accidentsArray = responseObj[@"data"][@"accidents"];
           
            for (int i = 0; i < accidentsArray.count; i++)
            {
                NSDictionary *dict = accidentsArray[i];
                
                AccidentsList *accidents = [AccidentsList mj_objectWithKeyValues:dict];
                
                [self.flow_Data_Array  addObject:accidents];
                
            }
           
            if (self.flow_Data_Array.count > 0)
            {
                [self.nullView removeFromSuperview];
            } else {
                [self.tableView addSubview:self.nullView];
            }
            
            [self.tableView reloadData];
            
        } else {
            
            [self.hud dismiss:YES];
            
            
            [WKProgressHUD popMessage:responseObj[@"message"] inView:self.view duration:1.5 animated:YES];
            
        }
        
        
    } failed:^(NSString *errorMsg) {
        NSLog(@"%@",errorMsg);
    }];
    
    
}

#pragma mark -
#pragma mark - 设置UI
- (void)setUpUI {
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
    
    ///1. 添加导航栏
    [self.view addSubview:self.topBackView];
    
    ///2. 添加表视图
    [self.view addSubview:self.tableView];
    
    ///3. 添加上下拉刷新空控件
    [self addMJRefresh];
    
}


/**
    MJRefresh
 */
- (void)addMJRefresh{
 
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(downRefresh)];
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(upRefresh)];
    
}
- (void)downRefresh{
    
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
    self.pageNo = 1;
    [self judgeNetWork];
}
- (void)upRefresh{
    
    if (self.pageNo != (int)self.pageTotal) {
        self.pageNo ++;
        [self judgeNetWork];
        [self.tableView.mj_footer endRefreshing];
    }else{
        self.tableView.mj_footer.state = MJRefreshStateNoMoreData;
    }
    [self.tableView.mj_header endRefreshing];
}

#pragma mark -
#pragma mark - 判断是否有网
- (void)judgeNetWork{
    if (![RLNetworkHelper isConnectedToNetwork])
    {
        [self.tableView addSubview:self.netView];
        self.hud = [WKProgressHUD showInView:self.view withText:@"加载中" animated:YES];
    }
    else
    {
        [self.netView removeFromSuperview];
        [self getDataToServer];
    }
}


//无网络状态
- (void)NoNetPressBtn{
    if ([RLNetworkHelper isConnectedToNetwork]) {
        [self.netView removeFromSuperview];
        [self getDataToServer];
    } else {
        [self.hud dismiss:YES];
    }
}






#pragma mark -
#pragma mark - UITableView协议
- (NSInteger)tableView:(UITableView *)tableView
 numberOfRowsInSection:(NSInteger)section{
    return self.flow_Data_Array.count;
}
- (CGFloat)tableView:(UITableView *)tableView
heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 80 * kHeight;
}
- (CGFloat)tableView:(UITableView *)tableView
heightForHeaderInSection:(NSInteger)section{
    return cellHeight;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
        cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    RecordCell *cell = [tableView dequeueReusableCellWithIdentifier:@"recordCell"];
    if (!cell)
    {
        cell = [[RecordCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"recordCell"];
    }
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.timeLabel.text = [NSString stringWithFormat:@"%@",self.flow_Data_Array[indexPath.row].showDate];
    
    //NSLog(@"%@, %@", cell.timeLabel.text, self.flow_Data_Array[indexPath.row].attachVos);
    
    cell.addressLabel.text = [NSString stringWithFormat:@"%@-%@--%@-%@",
                              self.flow_Data_Array[indexPath.row].departProvince,
                              self.flow_Data_Array[indexPath.row].departCity,
                              self.flow_Data_Array[indexPath.row].arrivalProvince,
                              self.flow_Data_Array[indexPath.row].arrivalCity];
    cell.styleLabel.text = [NSString stringWithFormat:@"%@",self.flow_Data_Array[indexPath.row].vehicleTypeName];
    return cell;
    
    
}
- (UIView *)tableView:(UITableView *)tableView
viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc]init];
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(18, 0, 200, cellHeight)];
    label.text = @"申报纪录";
    [view addSubview:label];
    
    UILabel *label1 = [[UILabel alloc]initWithFrame:CGRectMake(0, cellHeight - 0.5, screenWidth, 0.5)];
    label1.backgroundColor = LineGrayColor;
    [view addSubview:label1];
    
    
    view.backgroundColor = WhiteColor;
    return view;
}
- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    OrderdetailVC *detailVC = [[OrderdetailVC alloc]init];
    detailVC.orderID = [NSString stringWithFormat:@"%@",self.flow_Data_Array[indexPath.row].waybillId];
    
    [self.navigationController pushViewController:detailVC animated:YES];

}




#pragma mark -
#pragma mark - 导航栏点击
- (void)naviRightButtonClick {
    NSString *urlString = [NSString stringWithFormat:@"%@waybill/currentwaybill",Main_interface];
    [Common requestWithUrlString:urlString
                     contentType:application_json
                       errorShow:YES
                        finished:^(id responseObj) {
        
        if ([responseObj[@"data"] isEqual:[NSNull null]] || [responseObj[@"data"] count] < 1) {
            //此时证明没有在途运单
            [WKProgressHUD popMessage:@"暂无可申报运单"
                               inView:self.view
                             duration:1.5
                             animated:YES];
        }
        else
        {
            if ([responseObj[@"data"][@"auditStatus"] integerValue] != 0)
            {
                ScanVC *scanVC = [[ScanVC alloc]init];
                scanVC.orderId = responseObj[@"data"][@"id"];
                scanVC.statusId = [responseObj[@"data"][@"auditStatus"] integerValue];
                scanVC.orderNumber = responseObj[@"data"][@"orderCode"];
                [self.navigationController pushViewController:scanVC animated:YES];
            }
            else
            {
                DeclareViewController *declareVC = [[DeclareViewController alloc]init];
                declareVC.orderId = responseObj[@"data"][@"id"];
                declareVC.orderString = responseObj[@"data"][@"orderCode"];
                [self.navigationController pushViewController:declareVC animated:YES];
            }
        }
    }
    failed:^(NSString *errorMsg)
    {
        NSLog(@"%@",errorMsg);
    }];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
        
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:YES];
    
    RootViewController *rootVC = [RootViewController defaultsTabBar];
    
    [rootVC setTabBarHidden:NO];
}





@end
